/*
 * Copyright 2007-2008 Michele Mostarda ( michele.mostarda@gmail.com ).
 * All Rights Reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.michelemostarda.ant;

import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.types.resources.FileResourceIterator;
import org.michelemostarda.Converter;

import java.io.*;
import java.util.List;
import java.util.ArrayList;

/**
 * This <i>Ant</i> task exposes the the functionalities of the
 * {@link org.michelemostarda.Converter} object.
 */
public class ConverterTask extends Task {

    /**
     * The fileset of wiki pages to be processed.
     */
    private List<FileSet> fileSets;

    /**
     * The output dir for the generated HTML pages.
     */
    private File outDir;

    /**
     * Internal converter.
     */
    private Converter converter;

    /**
     * Constructor.
     */
    public ConverterTask() {
        super();
        fileSets = new ArrayList<FileSet>();
        converter = new Converter();
    }

    /**
     * Sets the output directory.
     *
     * @param dir
     */
    public void setOutDir(File dir) {
        if(dir == null) {
            throw new IllegalArgumentException();
        }
        outDir = dir;
    }

    public void addFileSet(FileSet fs) {
        fileSets.add(fs);
    }

    public void execute() throws BuildException {
        if( ! outDir.exists() ) {
            outDir.mkdirs();
        }

        for(FileSet fs : fileSets) {
            processFileSet(fs);
        }
    }

    protected void processFileSet(FileSet fs) {
         try {
            FileResourceIterator files = (FileResourceIterator) fs.iterator();
            FileResource fileResource;
            while(files.hasNext()) {
                fileResource = files.nextResource();
                processFile(fileResource);
            }
        } catch (IOException ioe) {
            throw new BuildException(ioe);
        }
    }

    /**
     * Processes a single file resource.
     *
     * @param fr
     * @throws IOException
     */
    protected void processFile(FileResource fr) throws IOException {
        String outFileName = removeExtension( fr.getFile().getName() ) + ".html";
        File outFile =  new File(outDir, outFileName);
        if(! outFile.exists()) {
            outFile.createNewFile();
        }
        OutputStream os = new FileOutputStream(outFile);
        try {
            converter.parseUnit(fr.getFile(), new PrintStream(os));
        } finally {
            os.close();
        }
    }

    /**
     * Extracts the file name removing the extension.
     * 
     * @param fileName
     * @return
     */
    private String removeExtension(String fileName) {
        int i = fileName.lastIndexOf(".");
        return fileName.substring(0, i);
    }

}
